package com.sc.ktapplication.module.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.sc.ktapplication.R
import com.sc.ktapplication.common.base.BaseActivity
import com.sc.ktapplication.common.util.RsaUtils.EncryptUtils
import com.sc.ktapplication.common.util.ToastUtil
import kotlinx.android.synthetic.main.activity_update_pwd.*

class UpdatePwdActivity : BaseActivity() {

    private val viewModel by viewModels<UpdatePwdViewModel>()

    override fun getLayoutId(): Int {
       return R.layout.activity_update_pwd
    }

    override fun showErrorMsg() {
       showErrorMsg(etOldPwd,viewModel)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.updateRet.observe(this, Observer{ updateRet ->
            dismissLoadingDialog()
            if (updateRet) {
                ToastUtil.snackbarShort(etOldPwd, "密码修改成功！")
                finish()
            }
        })
    }

    fun update(view: View) {
        if (!validate()) return
        showLoadingDialog("正在修改，请稍后...", false)

        val oldPwd: String = etOldPwd.text.toString()
        val newPwd: String = etPassword.text.toString()
        val params = hashMapOf<String,Any>()
        params["oldPassword"] =  EncryptUtils.encryptMD5ToString(oldPwd)
        params["password"] =EncryptUtils.encryptMD5ToString(newPwd)
        viewModel.updatePwd(params)
    }

    private fun validate(): Boolean {
        val oldPwd: String =etOldPwd.text.toString()
        val newPwd: String = etPassword.text.toString()
        val surePwd: String = etSurePassword.text.toString()
        if (TextUtils.isEmpty(oldPwd)) {
            ToastUtil.snackbarShort(etOldPwd,"请输入原密码！")
            return false
        }
        if (TextUtils.isEmpty(newPwd)) {
            ToastUtil.snackbarShort(etOldPwd,"请输入新密码！")
            return false
        }
        if (TextUtils.isEmpty(surePwd)) {
            ToastUtil.snackbarShort(etOldPwd,"请输入确认密码！")
            return false
        }
        if (newPwd.length < 6) {
            ToastUtil.snackbarShort(etOldPwd,"新密码长度至少6位！")
            return false
        }
        if (newPwd != surePwd) {
            ToastUtil.snackbarShort(etOldPwd,"新密码两次输入不一致！")
            return false
        }
        return true
    }
}